<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="equipmentCode">
        <el-input
          v-model="queryParams.equipmentCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select v-model="queryParams.equipmentType" placeholder="请选择设备类型" clearable>
          <el-option
            v-for="dict in equipment_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="所属生产线ID" prop="lineId">
        <el-input
          v-model="queryParams.lineId"
          placeholder="请输入所属生产线ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="所属生产线" prop="lineId">
        <el-select
          v-model="queryParams.lineId"
          placeholder="请选择所属生产线"
          clearable
          filterable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in lineOptions"
            :key="item.lineId"
            :label="item.lineName"
            :value="item.lineId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option
            v-for="dict in equipment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="制造商" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="请输入制造商"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购买日期" style="width: 308px">
        <el-date-picker
          v-model="daterangePurchaseDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="保修期" style="width: 308px">
        <el-date-picker
          v-model="daterangeWarrantyPeriod"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="维护周期(天)" prop="maintenanceCycle">
        <el-input
          v-model="queryParams.maintenanceCycle"
          placeholder="请输入维护周期(天)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上次维护时间" prop="lastMaintenance">
        <el-date-picker clearable
          v-model="queryParams.lastMaintenance"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择上次维护时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['dm:equipment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dm:equipment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dm:equipment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['dm:equipment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="equipmentId" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="设备编号" align="center" prop="equipmentCode" />
      <el-table-column label="设备类型" align="center" prop="equipmentType">
        <template #default="scope">
          <dict-tag :options="equipment_type" :value="scope.row.equipmentType"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属生产线ID" align="center" prop="lineId" /> -->
      <el-table-column label="所属生产线" align="center" prop="lineName">
          <template #default="scope">
            <span>{{ scope.row.lineName || '-' }}</span>
          </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="equipment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="制造商" align="center" prop="manufacturer" />
      <el-table-column label="购买日期" align="center" prop="purchaseDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保修期" align="center" prop="warrantyPeriod" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.warrantyPeriod, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护周期(天)" align="center" prop="maintenanceCycle" />
      <el-table-column label="上次维护时间" align="center" prop="lastMaintenance" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastMaintenance, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dm:equipment:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dm:equipment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="equipmentRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="equipmentCode">
              <el-input v-model="form.equipmentCode" placeholder="请输入设备编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentType">
              <el-select v-model="form.equipmentType" placeholder="请选择设备类型" style="width: 100%">
                <el-option
                  v-for="dict in equipment_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择设备状态" style="width: 100%">
                <el-option
                  v-for="dict in equipment_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属生产线" prop="lineId">
              <el-input v-model="form.lineName" placeholder="请选择生产线" disabled>
                <template #append>
                  <el-button type="primary" @click="handleSelectLine">选择生产线</el-button>
                </template>
              </el-input>
              <el-input v-model="form.lineId" type="hidden" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护周期(天)" prop="maintenanceCycle">
              <el-input v-model="form.maintenanceCycle" placeholder="请输入维护周期(天)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择购买日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保修期" prop="warrantyPeriod">
              <el-date-picker
                v-model="form.warrantyPeriod"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择保修期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次维护时间" prop="lastMaintenance">
              <el-date-picker
                v-model="form.lastMaintenance"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择上次维护时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <LineSelect ref="lineSelectRef" />
  </div>
</template>

<script setup name="Equipment">
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment, listLine } from "@/api/dm/equipment";
import { generateEquipmentCode } from "@/utils/generator";
// 导入LineSelect组件
import LineSelect from '@/components/LineSelect/index.vue';

const { proxy } = getCurrentInstance();
const { equipment_status, equipment_type } = proxy.useDict('equipment_status', 'equipment_type');
const lineOptions = ref([]); // 生产线选项
const equipmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangePurchaseDate = ref([]);
const daterangeWarrantyPeriod = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentName: null,
    equipmentCode: null,
    equipmentType: null,
    lineId: null,
    status: null,
    manufacturer: null,
    purchaseDate: null,
    warrantyPeriod: null,
    maintenanceCycle: null,
    lastMaintenance: null,
  },
  rules: {
    equipmentName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    equipmentCode: [
      { required: true, message: "设备编号不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "设备状态不能为空", trigger: "blur" }
    ],
    equipmentType:[
      { required: true, message: "设备类型不能为空", trigger: "blur" }
    ],
    
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangePurchaseDate && '' != daterangePurchaseDate) {
    queryParams.value.params["beginPurchaseDate"] = daterangePurchaseDate.value[0];
    queryParams.value.params["endPurchaseDate"] = daterangePurchaseDate.value[1];
  }
  if (null != daterangeWarrantyPeriod && '' != daterangeWarrantyPeriod) {
    queryParams.value.params["beginWarrantyPeriod"] = daterangeWarrantyPeriod.value[0];
    queryParams.value.params["endWarrantyPeriod"] = daterangeWarrantyPeriod.value[1];
  }
  listEquipment(queryParams.value).then(response => {
    equipmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    equipmentId: null,
    equipmentName: null,
    equipmentCode: null,
    equipmentType: null,
    lineId: null,
    status: null,
    manufacturer: null,
    purchaseDate: null,
    warrantyPeriod: null,
    maintenanceCycle: null,
    lastMaintenance: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("equipmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangePurchaseDate.value = [];
  daterangeWarrantyPeriod.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.equipmentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 自动生成设备编号
  form.value.equipmentCode = generateEquipmentCode();
  open.value = true;
  title.value = "添加设备管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _equipmentId = row.equipmentId || ids.value
  getEquipment(_equipmentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["equipmentRef"].validate(valid => {
    if (valid) {
      if (form.value.equipmentId != null) {
        updateEquipment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEquipment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _equipmentIds = row.equipmentId || ids.value;
  proxy.$modal.confirm('是否确认删除设备管理编号为"' + _equipmentIds + '"的数据项？').then(function() {
    return delEquipment(_equipmentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dm/equipment/export', {
    ...queryParams.value
  }, `equipment_${new Date().getTime()}.xlsx`)
}

// 在setup中添加
const lineSelectRef = ref();

// 添加选择生产线方法
function handleSelectLine() {
  if (!lineSelectRef.value) {
    proxy.$modal.msgError("生产线选择组件初始化失败");
    return;
  }
  
  try {
    lineSelectRef.value.show();
    
    // 设置选择回调
    lineSelectRef.value.onSelect((selectedLine) => {
      form.value.lineId = selectedLine.lineId;
      form.value.lineName = selectedLine.lineName; // 新增名称绑定
    });
  } catch (error) {
    proxy.$modal.msgError("打开生产线选择失败：" + error.message);
    console.error(error);
  }
}

// 在组件挂载时获取生产线选项
onMounted(() => {
  // 获取生产线列表
  // 这里调用API获取生产线列表
  // 示例代码，需要根据实际API调整
  listLine().then(response => {
    lineOptions.value = response.rows || response.data;
  });
});

getList();
</script>
